package com.zyc.remoting.transport.netty.coder;

import com.zyc.serialize.Serializer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageCodec;
import io.netty.handler.codec.MessageToByteEncoder;

/**
 * @author zyc
 * @create 2022-06-04-16:18
 */
public class NettyRpcEncoder extends MessageToByteEncoder {
    private final Serializer serializer;
    private final Class<?> genericClass;

    public NettyRpcEncoder(Serializer serializer, Class<?> genericClass) {
        this.serializer = serializer;
        this.genericClass = genericClass;
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, Object o, ByteBuf byteBuf) throws Exception {
        if (genericClass.isInstance(o)) {
            byte[] bytes = serializer.serialize(o);
            int dataLength = bytes.length;

            // 写入消息的长度在头部，writerIndex + 4;
            byteBuf.writeInt(dataLength);
            byteBuf.writeBytes(bytes);
        }
    }
}
